package org.example.reemploymentsys.service;

import org.example.reemploymentsys.entity.Exam;
import org.example.reemploymentsys.entity.ExamQuestion;
import org.example.reemploymentsys.entity.Organization;
import org.example.reemploymentsys.entity.UserTb;
import org.example.reemploymentsys.pojo.ExamData;
import org.example.reemploymentsys.repository.ExamQuestionRe;
import org.example.reemploymentsys.repository.ExamRe;
import org.example.reemploymentsys.repository.OrganizationRe;
import org.example.reemploymentsys.repository.UserTbRe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class ExamService {
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private OrganizationRe organizationRe;
    @Autowired
    ExamQuestionRe examQuestionRe;
    @Autowired
    private ExamRe examRe;
    public List<ExamQuestion> generateExam(ExamData exam) {
        String OrganizationId= userTbRe.findOrgizationIdByUsername(exam.getUsername());
        Organization organization = organizationRe.findOrganizationById(OrganizationId);
        UserTb user = userTbRe.findUserByRoleName("superAdmin");
        Exam exam1 = new Exam();
        exam1.setOrganization(organization);
        exam1.setDuration(exam.getDuration());
        exam1.setName(exam.getName());
        exam1.setTotalScore(exam.getTotalScore());
        exam1.setDescription(exam.getDescription());
        List<ExamQuestion> singleExamQuestions = examQuestionRe.findByUserOrOrganizationAndQuestionType(user, organization, "单选");
        // 打乱单选列表顺序
        Collections.shuffle(singleExamQuestions);
        // 获取单选列表指定条条记录
        List<ExamQuestion> singleQuestions= singleExamQuestions.subList(0, exam.getSingleChoiceCount());
        List<ExamQuestion> multipleExamQuestions = examQuestionRe.findByUserOrOrganizationAndQuestionType(user, organization, "多选");
        // 打乱多选列表顺序
        Collections.shuffle(multipleExamQuestions);
        // 获取多选列表指定条条记录
        List<ExamQuestion> multipleQuestions= multipleExamQuestions.subList(0, exam.getMultipleChoiceCount());
        List<ExamQuestion> shortExamQuestions = examQuestionRe.findByUserOrOrganizationAndQuestionType(user, organization, "简答");
        // 打乱单选列表顺序
        Collections.shuffle(shortExamQuestions);
        // 获取单选列表指定条条记录
        List<ExamQuestion> shortQuestions= shortExamQuestions.subList(0, exam.getShortAnswerCount());
        List<ExamQuestion> allQuestions = new ArrayList<>();
        allQuestions.addAll(singleQuestions);
        allQuestions.addAll(multipleQuestions);
        allQuestions.addAll(shortQuestions);
        exam1.setQuestions(allQuestions);
        examRe.save(exam1);

        return allQuestions;
    }
}
